/**
 * 
 */
package it.fuesi.myseries.api;

import it.fuesi.myseries.model.MySeriesConstant;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

/**
 * @author fuesi
 * 
 */
public class ApiBrokerService extends IntentService {

	public ApiBrokerService() {
		super("ApiBrokerService");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.IntentService#onHandleIntent(android.content.Intent)
	 */
	@Override
	protected void onHandleIntent(Intent intent) {
		final Bundle extras = intent.getExtras();
		Bundle results = null;
		if(isOnline()){
			
			final ApiMethod cmd = (ApiMethod)extras.get(MySeriesConstant.API_METHOD.toString());
			
			final AbstractApiTask task = cmd.getApiTask();
			
			task.setContext(extras, this);
			
			final Map<String,String> params = task.getApiParams();
			
			final ApiClient client = ApiClient.getInstance();
			
			
			
			
			try {
				final JSONObject response = client.callMethod(cmd, params);
				results = task.processResults(response);
			} catch (JSONException e) {
				results = new Bundle();
				results.putBoolean(MySeriesConstant.SUCCESS.toString(), false);
				results.putString(MySeriesConstant.ERROR.toString(), e.getMessage());
			}
		}else{
			results = new Bundle();
			results.putBoolean(MySeriesConstant.SUCCESS.toString(), false);
			results.putString(MySeriesConstant.ERROR.toString(), "No connectivity");
		}
		
		
		final Messenger msg = (Messenger) extras.get(MySeriesConstant.MESSENGER
				.toString());
		
		Message message = Message.obtain();
		
		final Bundle returnBundle = new Bundle();
		
		returnBundle.putBundle(MySeriesConstant.RESULTS.toString(), results);
		message.setData(returnBundle);
		
		try {
			msg.send(message);
		} catch (RemoteException e) {
			System.out.println("Remote Exception: " + e.getMessage());
			e.printStackTrace();
		}
		
		
		
	}
	
	public boolean isOnline() {
	    ConnectivityManager cm =
	        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
	

	public static Intent getApiTaskIntent(Context context,
			ApiMethod apiMethod) {
		
		Intent intent = new Intent(context, ApiBrokerService.class);

		Handler handler = new ApiBrokerServiceHandler(context);

		intent.putExtra(MySeriesConstant.MESSENGER.toString(), new Messenger(
				handler));
		intent.putExtra(MySeriesConstant.API_METHOD.toString(),apiMethod );
		
		return intent;
	}
	


}
